//
//  OperationDataBaseModel.m
//  QRMaster
//
//  Created by myApple on 15/12/21.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "OperationDataBaseModel.h"
#import "FMDatabase.h"

@implementation OperationDataBaseModel


+(FMDatabaseQueue *)shareFMDatabaseQueue
{
    NSArray *paths = HomePathArray;
    NSString *documents = [paths objectAtIndex:0];
    NSString *database_path = [documents stringByAppendingPathComponent:@"ma_db.db"];
//    DDLOG([NSString stringWithFormat:@"%@",database_path],nil);
    static FMDatabaseQueue * queue = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue = [FMDatabaseQueue databaseQueueWithPath:database_path];
    });
    return queue;
}

#pragma mark -------------------- 插入数据
-(void)insertDataTable:(NSString *)tableName withDict:(NSMutableDictionary *)dict
{
    NSMutableString * keyString = [[NSMutableString alloc]init];
    NSMutableString * valueString = [[NSMutableString alloc]init];
    for (NSString * string in [dict allKeys]) {
        [keyString appendString:[NSString stringWithFormat:@"%@,",string]];
        [valueString appendString:[NSString stringWithFormat:@"'%@',",[dict objectForKey:string]]];
    }
    keyString = [self rangeString:keyString];
    valueString = [self rangeString:valueString];
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        BOOL insertStatus = YES;
        insertStatus = [db executeUpdate:[NSString stringWithFormat:@"REPLACE INTO %@ (%@) VALUES (%@)",tableName,keyString,valueString]];
//        DDLOG([NSString stringWithFormat:@"REPLACE INTO %@ (%@) VALUES (%@)",tableName,keyString,valueString],nil);
        if (!insertStatus) {
            * rollback = YES;
//            DDLOG(@"update fail",nil);
        }
        else
        {
//            DDLOG(@"update success",nil);
        }
    }];
}


#pragma mark ---------------------- 查询数据
-(void)queryDataFromTable:(NSString *)tableName withCondition:(NSString *)condition block:(resultBlock)resultSet
{
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inDatabase:^(FMDatabase *db) {
        FMResultSet * set = [db executeQuery:[NSString stringWithFormat:@"select * from %@ %@",tableName,condition]];
//        DDLOG([NSString stringWithFormat:@"select * from %@ %@",tableName,condition],nil);
        
        if (resultSet) {
            resultSet(set);
        }
    }];
}

#pragma mark ------------------------删除数据
-(void)deleteDataFromTable:(NSString *)tableName withCondition:(NSString *)condition
{
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        BOOL insertStatus = YES;
        insertStatus = [db executeUpdate:[NSString stringWithFormat:@"delete from %@ %@",tableName,condition]];
//        DDLOG([NSString stringWithFormat:@"delete from %@ %@",tableName,condition],nil);
        if (!insertStatus) {
            * rollback = YES;
//            DDLOG(@"delete fail",nil);
        }
        else
        {
//            DDLOG(@"delete success",nil);
        }
    }];
}


#pragma mark --------------------------更新数据
-(void)updateDataFromTable:(NSString *)tableName withCondition:(NSString *)condition withDict:(NSMutableDictionary *)dict
{
    NSString *sqlStr=@"";
    NSMutableString * valueString = [[NSMutableString alloc]init];
    for (NSString * string in [dict allKeys]) {
        [valueString appendString:[NSString stringWithFormat:@"%@ = '%@',",string,[self getStr:[NSString stringWithFormat:@"%@",[dict objectForKey:string]]]]];
    }
    sqlStr=[valueString substringToIndex:valueString.length-1];
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        BOOL insertStatus = YES;
        insertStatus = [db executeUpdate:[NSString stringWithFormat:@"UPDATE %@ SET %@ %@",tableName,sqlStr,condition]];
//        DDLOG([NSString stringWithFormat:@"UPDATE %@ SET %@ %@",tableName,sqlStr,condition],nil);
        if (!insertStatus) {
            * rollback = YES;
        }
    }];
}


#pragma mark --------------------删除表数据
-(void)truncateTable
{
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        BOOL insertStatus = YES;
        insertStatus &= [db executeUpdate:@"delete from communityInfo"];
        insertStatus &= [db executeUpdate:@"delete from customers"];
        insertStatus &= [db executeUpdate:@"delete from groupInfo"];
        insertStatus &= [db executeUpdate:@"delete from groupMembers"];
        insertStatus &= [db executeUpdate:@"delete from member"];
        insertStatus &= [db executeUpdate:@"delete from userInfo"];
        insertStatus &= [db executeUpdate:@"delete from buildingInfo"];
        insertStatus &= [db executeUpdate:@"delete from floorsInfo"];
        insertStatus &= [db executeUpdate:@"delete from roomsInfo"];
        insertStatus &= [db executeUpdate:@"delete from buildingInfo_customer"];
        insertStatus &= [db executeUpdate:@"delete from floorsInfo_customer"];
        insertStatus &= [db executeUpdate:@"delete from roomsInfo_customer"];
        insertStatus &= [db executeUpdate:@"delete from collectionCard"];
        if (!insertStatus) {
            * rollback = YES;
        }
        
    }];
}


#pragma mark -----------------查询时间戳
-(NSString *)getTimeFromTable:(NSString *)tableName selectTime:(NSString *)key withCondition:(NSString *)condition
{
    __block NSString * timeKeyStr;
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inDatabase:^(FMDatabase *db) {
            FMResultSet * set = [db executeQuery:[NSString stringWithFormat:@"select %@ from %@ %@",key,tableName, condition]];
            while ([set next]) {
                timeKeyStr = [set stringForColumn:key];
            }
        
    }];
    return timeKeyStr;
}

#pragma mark --------------------------通过集群删除数据
-(void)deleteDataFromTableByCommunityId:(NSString *)tableName communityId:(NSString *)communityId
{
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inDatabase:^(FMDatabase *db) {
            NSString * sqlStr=[NSString stringWithFormat:@"delete from %@ where communityId = %@",tableName,communityId];
            BOOL re = YES;
            re = [db executeUpdate:sqlStr];
    }];

}


#pragma mark ----------------通过集群ID来删除楼栋 楼层 或者 房间
-(void)deleteBulidingFromTableByCommunityId:(NSString *)tableName communityId:(NSString *)communityId
{
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inDatabase:^(FMDatabase *db) {
        NSString * sqlStr=[NSString stringWithFormat:@"delete from %@ where communityentity_id = %@",tableName,communityId];
        BOOL re = YES;
        re = [db executeUpdate:sqlStr];
    }];
}

#pragma mark -----删除表
-(void)deleteTable:(NSString *)tableName
{
    FMDatabaseQueue * queue = [OperationDataBaseModel shareFMDatabaseQueue];
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        BOOL insertStatus = YES;
        NSString *sqlStr=[NSString stringWithFormat:@"delete from %@",tableName];
        insertStatus = [db executeUpdate:sqlStr];
        
        if (!insertStatus) {
            * rollback = YES;
            
        }
        
    }];
}

-(NSString *)getStr:(NSString *)str
{
    NSString *returnStr=@"";
    if (str==nil || [@"" isEqualToString:str]==YES || str.length==0 ) {
        returnStr=@"";
    }
    else
    {
        returnStr=str;
    }
    return returnStr;
}
/**
 *  去掉字符串最后一个逗号
 *
 *  @param mutableString 需要去掉逗号的字符串
 *
 *  @return 处理逗号后的字符串
 */
-(NSMutableString *)rangeString:(NSMutableString *)mutableString
{
    NSRange Range;
    Range.location = mutableString.length - 1;
    Range.length = 1;
    [mutableString deleteCharactersInRange:Range];
    return mutableString;
}

@end
